<template>
  <div ref="pdfContainer" class="pdf-container"></div>
  <contextHolder />
</template>

<script lang="ts" setup>
  import { ref, defineProps } from 'vue';
  import { useGetFileDataApi } from '@/api/demo/assess';
  import { useUserStore } from '@/store/modules/user';
  import { notification } from 'ant-design-vue';

  const props = defineProps({
    url: String,
  });

  const pdfContainer = ref<any>(null);
  const [api, contextHolder] = notification.useNotification();
  console.log('pdf执行');

  if (props.url) {
    useGetFileDataApi({
      userid: useUserStore().userInfo?.userId,
      filePath: props.url,
    }).then((res) => {
      if (res.status === 200 && res.data.success) {
        loadPdf(res.data.file);
      } else {
        api.error({
          message: res.data.message,
          placement: 'topRight',
        });
      }
    });
  }

  async function loadPdf(file) {
    const loadingTask = (window as any).pdfjsLib.getDocument(file);
    const scale = 1.5;

    const pdf = await loadingTask.promise;
    // 渲染所有页面到canvas上
    var renderPage = function (num) {
      pdf.getPage(num).then(function (page) {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var viewport = page.getViewport({ scale: scale });

        // 调整canvas的高度以容纳新的页面
        canvas.height += viewport.height;
        canvas.width = viewport.width;

        // 渲染页面到canvas上
        var renderContext = {
          canvasContext: context,
          viewport: viewport,
        };

        var renderTask = page.render(renderContext);
        renderTask.promise.then(function () {
          // 将canvas添加到容器中
          canvas.classList.add('pdf-page');
          if (pdfContainer.value) {
            pdfContainer.value.appendChild(canvas);
          }
          // 页面渲染完成，继续渲染下一页（如果有）
          if (num + 1 <= pdf.numPages) {
            renderPage(num + 1);
          } else {
            console.log('All pages rendered');
          }
        });
      });
    };

    // 从第一页开始渲染
    renderPage(1);
  }
</script>

<style scoped>
  .pdf-container {
    width: 100%;
    height: 100vh;
    overflow: auto;
    text-align: center;
  }
</style>
